package org.tc.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.tc.bean.Item;
import org.tc.bean.ItemDesc;
import org.tc.common.Result;
import org.tc.service.ItemDescService;
import org.tc.service.ItemService;
import org.tc.utils.HttpClientUtil;
import org.tc.utils.JsonUtils;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Date;

/**
 * Created by zxd on 2018/1/26.
 */
@Service
public class ItemServiceImpl extends BaseServiceImpl<Item> implements ItemService {

    private Logger LOGGER= LoggerFactory.getLogger(ItemServiceImpl.class);

    @Autowired
    private JmsTemplate jmsTemplate;

    public static final  String DELETE_CACHE_URL="http://www.yufan.com/api/item/cache/delete/";

    @Autowired
    private ItemDescService itemDescService;

    @Override
    public void saveItem(Item item, String desc) {

        if(item==null|| StringUtils.isEmpty(desc)){
            return;
        }

        //强制设置id为空
        item.setId(null);
        //设置商品状态为下架
        item.setStatus(Item.ITEM_STATUS_NO);
        item.setCreated(new Date());
        item.setUpdated(item.getCreated());
        //保存商品基本数据
        this.save(item);

        //保存描述信息
        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(item.getCreated());
        itemDesc.setCreated(item.getCreated());
        itemDescService.save(itemDesc);
    }

    @Override
    public void updateItem(Item item, String desc) {
        if(item==null|| StringUtils.isEmpty(desc)){
            return;
        }
        //设置修改商品的时间
        item.setUpdated(new Date());
        this.update(item);

        //修改描述信息
        ItemDesc itemDesc = itemDescService.queryById(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(item.getUpdated());
        itemDescService.update(itemDesc);

        //调用前台系统暴露的的接口，删除缓存

        /*
        String json = HttpClientUtil.doGet(DELETE_CACHE_URL + item.getId());
        Result result = JsonUtils.jsonToPojo(json, Result.class);

        if(result.getStatus().equals("success")){
            LOGGER.info("删除缓存成功!itemId{}",item.getId());
        }
        */

        //使用mq通知   消息生产者
        jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                LOGGER.info("商品id为{}，向mq发送消息",item.getId());
                return session.createTextMessage(String.valueOf(item.getId()));
            }
        });
    }


}
